#ifndef __TIMERQUEUE_H__
#define __TIMERQUEUE_H__

#include "Timer.h"
#include <vector>
#include <set>
#include <map>
#include <chrono>
#include <memory>
#include <atomic>

class TimerQueue
{
public:
    TimerQueue();
    ~TimerQueue();
    
    // 添加定时器，返回定时器ID
    int64_t addTimer(std::chrono::milliseconds delay,
                     std::chrono::milliseconds interval,
                     TimerCallback &&callback);
    
    // 取消定时器
    void cancelTimer(int64_t timerId);
    
    // 获取timerfd文件描述符
    int getTimerFd() const { return _timerfd; }
    
    // 处理到期的定时器
    void handleExpiredTimers();
    
private:
    using TimerEntry = std::pair<std::chrono::steady_clock::time_point, int64_t>;
    using TimerSet = std::set<TimerEntry>;
    using TimerMap = std::map<int64_t, TimerPtr>;
    
    void resetTimerFd();
    std::vector<TimerPtr> getExpiredTimers();
    void insertTimer(TimerPtr timer);
    
    int _timerfd;
    TimerSet _timers;           // 按到期时间排序的定时器集合
    TimerMap _activeTimers;     // 活跃定时器映射表
    std::atomic<int64_t> _timerIdCounter;
};

#endif